package com.hejielife.readwritelock1;

public final class ReadWriteLock {
	private int readingReaders = 0; // (A)正在读的操作
	private int waitingWriters = 0; // (B)准备写的操作
	private int writingWriters = 0; // (C)正在写的操作
	// 标志位，true写优先，false读优先.。如果读操作多，那么写操作就无法完成
	// 如果写操作多，那么读操作就无法完成。保证公平
	private boolean preferWriter = true;

	public synchronized void readLock() throws InterruptedException {
		while (writingWriters > 0 || (preferWriter && waitingWriters > 0)) {
			wait();
		}
		readingReaders++; // (A)读的操作++
	}

	public synchronized void readUnlock() {
		readingReaders--; // (A)读的操作--
		preferWriter = true;// 写优先
		notifyAll();
	}

	public synchronized void writeLock() throws InterruptedException {
		waitingWriters++; // (B)准备写的操作++
		try {
			while (readingReaders > 0 || writingWriters > 0) {
				wait();
			}
		} finally {
			waitingWriters--; // (B)准备写的操作--
		}
		writingWriters++; // (C)正在写的操作++
	}

	public synchronized void writeUnlock() {
		writingWriters--; // (C)正在写的操作--
		preferWriter = false;// 读优先
		notifyAll();
	}
}
